package cn.wowjoy.office.materialmanage.stock;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.arch.lifecycle.MediatorLiveData;
import android.arch.lifecycle.Observer;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;

import java.util.ArrayList;
import java.util.List;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseActivity;
import cn.wowjoy.office.common.customview.MaskFramLayout;
import cn.wowjoy.office.common.decoration.SimpleItemDecoration;
import cn.wowjoy.office.common.widget.CreateDialog;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.data.mock.PopuModel;
import cn.wowjoy.office.data.response.MaterialSearchResponse;
import cn.wowjoy.office.data.response.StockTypeResponse;
import cn.wowjoy.office.databinding.ActivityMaterialStockBinding;

@Route(path = "/materialmanage/stock/materialstock")
public class MaterialStockActivity extends NewBaseActivity<ActivityMaterialStockBinding, MaterialStockViewModel> implements View.OnClickListener {


    private float initHeight;
    private float stockHeight;
    private float materialHeight;
    private float typeHeight;
    private MediatorLiveData<Integer> type = new MediatorLiveData<>();
    private MDialog waitDialog;

    public MediatorLiveData<Integer> getType() {
        return type;
    }
    private String stroageCode;
    private String usageCode;

    private boolean isStockMenuFailed;
    private boolean isUsageMenuFailed;
    private boolean isTypeMenuFailed;


    @Override
    protected Class<MaterialStockViewModel> getViewModel() {
        return MaterialStockViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_material_stock;
    }

//    @Override
//    protected void onResume() {
//        super.onResume();
//        openBroadCast();
//
//    }
//
//    @Override
//    protected void onStop() {
//        super.onStop();
//        closeBroadCast();
//    }
//
//    @Override
//    protected void brodcast(Context context, String msg) {
//        super.brodcast(context, msg);
//        viewModel.setSearchWords(msg);
//        viewModel.getStockList(true);
//    }

    @Override
    protected void init(Bundle savedInstanceState) {
        binding.setViewmodel(viewModel);
        initView();
        initMenu();

        initObserver();
        viewModel.getStock();
    }
    private boolean isOpen = false;

    @Override
    protected ViewGroup getErrorViewRoot() {
        return binding.content;
    }

    @Override
    protected void refreshError() {
        super.refreshError();
        if (isStockMenuFailed){
            viewModel.getStock();
        } else if (isUsageMenuFailed){
            viewModel.getUsage(stroageCode);
        } else if (isTypeMenuFailed){
            viewModel.getTypeTree(usageCode);
        } else {
            viewModel.getStockList(true,viewModel.getIds());
        }

    }

    private void initObserver(){
        viewModel.stockMenu.observe(this, new Observer<LiveDataWrapper<List<PopuModel>>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<List<PopuModel>> listLiveDataWrapper) {
                switch (listLiveDataWrapper.status){
                    case LOADING:
                        clearDialog();
                        waitDialog = CreateDialog.waitingDialog(MaterialStockActivity.this);
                        break;
                    case SUCCESS:
                        waitDialog.dismiss();
                        isStockMenuFailed = false;
                        binding.stock.setText(listLiveDataWrapper.data.get(0).getName());
                        stockHeight= getResources().getDimensionPixelSize(R.dimen.height2)*listLiveDataWrapper.data.size();
                        stroageCode = listLiveDataWrapper.data.get(0).getCode();
                        viewModel.setStorageCode(stroageCode);
                        break;
                    case ERROR:
                        waitDialog.dismiss();
                        isStockMenuFailed = true;
                        handleException(listLiveDataWrapper.error,true);
                        break;
                }

            }
        });

        viewModel.usageMenu.observe(this, new Observer<LiveDataWrapper<List<PopuModel>>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<List<PopuModel>> listLiveDataWrapper) {
                switch (listLiveDataWrapper.status){
                    case LOADING:
                        clearDialog();
                        waitDialog = CreateDialog.waitingDialog(MaterialStockActivity.this);
                        break;
                    case SUCCESS:
                        waitDialog.dismiss();
                        isUsageMenuFailed = false;
                        binding.material.setText(listLiveDataWrapper.data.get(0).getName());
                        materialHeight= getResources().getDimensionPixelSize(R.dimen.height2)*listLiveDataWrapper.data.size();
                        usageCode = listLiveDataWrapper.data.get(0).getCode();
                        viewModel.setUsageCode(usageCode);
                        break;
                    case ERROR:
                        waitDialog.dismiss();
                        isUsageMenuFailed = true;
                        handleException(listLiveDataWrapper.error,true);
                        break;
                }
            }
        });
        viewModel.typeTree.observe(this, new Observer<LiveDataWrapper<StockTypeResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<StockTypeResponse> stockTypeResponseLiveDataWrapper) {
                switch (stockTypeResponseLiveDataWrapper.status){
                    case LOADING:
                        clearDialog();
                        waitDialog = CreateDialog.waitingDialog(MaterialStockActivity.this);
                        break;
                    case SUCCESS:
                        waitDialog.dismiss();
                        isTypeMenuFailed = false;
                        typeHeight= getResources().getDimensionPixelSize(R.dimen.height3);
                        viewModel.setIds(viewModel.mainTypeAdapter.getSelectIds());
                        break;
                    case ERROR:
                        waitDialog.dismiss();
                        isTypeMenuFailed = true;
                        handleException(stockTypeResponseLiveDataWrapper.error,true);
                        break;
                }
            }
        });
        viewModel.stockList.observe(this, new Observer<LiveDataWrapper<List<MaterialSearchResponse>>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<List<MaterialSearchResponse>> stockListResponseLiveDataWrapper) {
                switch (stockListResponseLiveDataWrapper.status) {
                    case LOADING:
                        clearDialog();
                        waitDialog = CreateDialog.waitingDialog(MaterialStockActivity.this);
                        break;
                    case SUCCESS:
                        waitDialog.dismiss();
                        break;
                    case ERROR:
                        waitDialog.dismiss();
                        handleException(stockListResponseLiveDataWrapper.error, true);
                        break;
                }
            }
        });
    }

    private void clearDialog(){
        if (waitDialog != null ){
            waitDialog.dismiss();
            waitDialog = null;
        }

    }
    private void initView(){
        binding.back.setOnClickListener(this);
        binding.search.setOnClickListener(this);
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.emptyView.emptyContent.setText("可搜索物资名称，规格型号，物资分类，条形码");
        binding.recyclerView.setEmptyView(binding.emptyView.getRoot());
        binding.recyclerView.setAdapter(viewModel.adapter);
        binding.recyclerView.addItemDecoration(new SimpleItemDecoration(this,SimpleItemDecoration.VERTICAL_LIST));
    }
    private void initMenu(){
        binding.menuFl.setBgAlapht(77);

        binding.stockRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        binding.stockRecyclerview.setAdapter(viewModel.stockType);
        binding.stockRecyclerview.addItemDecoration(new SimpleItemDecoration(this,SimpleItemDecoration.VERTICAL_LIST));

        binding.materialRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        binding.materialRecyclerview.setAdapter(viewModel.materialType);
        binding.materialRecyclerview.addItemDecoration(new SimpleItemDecoration(this,SimpleItemDecoration.VERTICAL_LIST));

        binding.mainTypeRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        binding.mainTypeRecyclerview.setAdapter(viewModel.mainTypeAdapter);

        binding.subTypeRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        binding.subTypeRecyclerview.setAdapter(viewModel.subTypeAdapter);

        binding.menuFl.setDimissListener(new MaskFramLayout.DimissListener() {
            @Override
            public void onDismiss() {

                closeFolder();
            }
        });

        binding.stockFl.setOnClickListener(this);
        binding.materialFl.setOnClickListener(this);
        binding.typeFl.setOnClickListener(this);

        binding.clearType.setOnClickListener(this);
        binding.complete.setOnClickListener(this);
        type.setValue(0);
        getType().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer integer) {
                switch (integer){
                    case 0:
                        binding.stock.setSelected(false);
                        binding.material.setSelected(false);
                        binding.type.setSelected(false);
                        break;
                    case 1:
                        binding.stock.setSelected(!isOpen);
                        binding.material.setSelected(false);
                        binding.type.setSelected(false);
                        break;
                    case 2:
                        binding.stock.setSelected(false);
                        binding.material.setSelected(!isOpen);
                        binding.type.setSelected(false);
                        break;
                    case 3:
                        binding.stock.setSelected(false);
                        binding.material.setSelected(false);
                        binding.type.setSelected(!isOpen);
                        break;

                }
            }
        });

        viewModel.menu.observe(this, new Observer<PopuModel>() {
            @Override
            public void onChanged(@Nullable PopuModel popuModel) {
                setFloder(popuModel);
                closeFolder();
            }
        });

    }


    private void showMenu(int type){
        binding.stockRecyclerview.setVisibility(1 == type ? View.VISIBLE : View.GONE);
        binding.materialRecyclerview.setVisibility(2 == type ? View.VISIBLE : View.GONE);
        binding.typeRecycler.setVisibility(3 == type ? View.VISIBLE : View.GONE);
    }
    private void handleFolder(){
        removeErrorview();
        switch (type.getValue()){
            case 1:
                initHeight= stockHeight;
                break;
            case 2:
                initHeight= materialHeight;
                break;
            case 3:
                initHeight= typeHeight;
                break;
        }

        if (isOpen){
            closeFolder();

        } else {
            openFolder();
        }
    }
    /**
     * 收起文件夹列表
     */
    private void closeFolder() {
        hideSoftInput();
        type.setValue(0);
        if (isOpen) {
            if (binding.contentFl.getHeight() != 0){
                initHeight = binding.contentFl.getHeight();
            }
            ObjectAnimator animator = ObjectAnimator.ofFloat(binding.contentFl, "translationY",
                    0,-initHeight).setDuration(300);
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    binding.contentFl.setVisibility(View.GONE);
                    binding.menuFl.setVisibility(View.GONE);
                }
            });
            animator.start();
            isOpen = false;
        }
    }
    /**
     * 弹出文件夹列表
     */
    private void openFolder() {
        hideSoftInput();
        if (!isOpen) {
            binding.menuFl.setVisibility(View.VISIBLE);
            if (binding.contentFl.getHeight() != 0){
                initHeight = binding.contentFl.getHeight();
            }
            ObjectAnimator animator = ObjectAnimator.ofFloat(binding.contentFl, "translationY",
                    -initHeight, 0).setDuration(300);
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationStart(Animator animation) {
                    super.onAnimationStart(animation);
                    binding.contentFl.setVisibility(View.VISIBLE);
                }
            });
            animator.start();
            isOpen = true;
        }
    }
    private void setFloder(PopuModel popuModel){
        if (type.getValue() == 1){
            binding.stock.setText(popuModel.getName());
            viewModel.getUsage(popuModel.getCode());
            stroageCode = popuModel.getCode();
            viewModel.setStorageCode(usageCode);
        } else {
            binding.material.setText(popuModel.getName());
            viewModel.getTypeTree(popuModel.getCode());
            usageCode = popuModel.getCode();
            viewModel.setUsageCode(usageCode);
        }

    }


    private void changeTab(int tt){
        if (type.getValue() > 0 && type.getValue() != tt && isOpen){
            isOpen = false;
            binding.menuFl.setVisibility(View.GONE);
        }
        showMenu(tt);
        type.setValue(tt);
        handleFolder();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.stock_fl:
                changeTab(1);
//                binding.stock.setSelected(isOpen);
//                handleFolder();
                break;
            case R.id.material_fl:
                changeTab(2);
//                binding.material.setSelected(isOpen);
//                handleFolder();
                break;
            case R.id.type_fl:
                changeTab(3);
//                binding.type.setSelected(isOpen);
//                handleFolder();
                break;
            case R.id.clear_type:
                viewModel.clear();
                break;
            case R.id.complete:
                viewModel.setIds(viewModel.mainTypeAdapter.getSelectIds());
                viewModel.setSearchWords("");
                viewModel.getStockList(true,viewModel.getIds());
                closeFolder();
                break;
            case R.id.back:
                onBackPressed();
                break;
            case R.id.search:
                ARouter.getInstance()
                        .build("/materialmanage/search/materialsearch")
                        .withString("storageCode",stroageCode)
                        .withString("usageCode",usageCode)
                        .withStringArrayList("slectedIds", (ArrayList<String>) viewModel.mainTypeAdapter.getSelectIds())
                        .navigation();
                break;

        }
    }
}
